package eu.webhib.frmwrk.service.utils;

import java.util.*;
import org.apache.log4j.Logger;

import eu.webhib.frmwrk.domain.intf.ParentChildEntity;

//
public class ServiceHelper {
   private static Logger log = Logger.getLogger(ServiceHelper.class);

   // not really needed
   /**
    * Add list items and all children to result list
    * @param rootList  list to add
    * @param result    resulting list with added items
    */
   private static <T extends ParentChildEntity> void addListWithChilds(List<T> rootList, List<T> result) {
      for (T entry : rootList) {
         result.add(entry);
         if (entry.getChildren() != null) {
            addListWithChilds(entry.getChildren(), result);
         }
      }
   }

   // not really needed
   public static <T extends ParentChildEntity> List<T> getTreeTransientChildren(List<T> list) {

      log.trace("getTreeTransientChildren: list " + list.size());
      List<T> topLevel = getTopLevelList(list);
      List<T> result = new LinkedList<T>();
      addListWithChilds(topLevel, result);

      log.info("getTreeTransientChildren: result " + result.size());
      assert (list.size() == result.size());
      return result;
   }

   public static <T extends ParentChildEntity> List<T> getTopLevelList(List<T> list) {

      log.trace("getTopLevelList: list " + list.size());
      /** need to clear the collections if method is called twice for the same EntityManager */
      for (T entry : list) {
         entry.clearChildren();
      }
      List<T> topLevel = new ArrayList<T>(50);
      for (T entry : list) {
         if (entry.getParent() == null) {
            /** is top level item so add to top level list */
            topLevel.add(entry);
         } else {
            /** wire into the children list */
            entry.getParent().getChildren().add(entry);
         }
      }
      return topLevel;
   }

}
